package com.example.shiwuyouproject.ui.modelview

import androidx.lifecycle.MutableLiveData
import com.example.shiwuyouproject.base.BaseViewModel
import com.example.shiwuyouproject.net.bean.User
import com.example.shiwuyouproject.net.http.BaseUserBean
import com.example.shiwuyouproject.utils.SPUtils
import com.example.shiwuyouproject.utils.SpConstant
import com.google.gson.Gson

/**
 * ls
 */
class LoginModelView : BaseViewModel() {
    private val loginRepository by lazy { RetrofitClient.getApiService() }
    val userLoginState = MutableLiveData<Boolean>()

    /**
     * 登录
     */
    fun userLogin(mobile: String, password: String) {
        launch(
            block = {
                val codeStatus = loginRepository.userLogin(mobile, password, "android")
                if (!codeStatus.success()) {
                    messageStatus.value = codeStatus.message()
                } else {
                    SPUtils.getInstance()
                        .put(SpConstant.USER_PHONE,mobile)
                    SPUtils.getInstance()
                        .put(SpConstant.USER_PWD,password)
                    SPUtils.getInstance()
                        .put(SpConstant.USER_INFO, Gson().toJson(codeStatus.result().userinfo()))
                    userLoginState.value = codeStatus.success()
                }
            },
            error = {
                userLoginState.value = false
                messageStatus.value = "网络错误，请重试！"
            },
            cancel = {

            },
            showErrorToast = false
        )
    }
    val getUserWxLoginStatus = MutableLiveData<BaseUserBean<User>>()
    /**
     * 微信登录
     */
    fun getUserWxLogin(wx_open_id: String, wx_uniq_id: String) {
        launch(
            block = {
                val codeStatus = loginRepository.getUserWxLogin(wx_open_id, wx_uniq_id, "android")
                    if(codeStatus.result().step=="2") {
                        SPUtils.getInstance()
                            .put(
                                SpConstant.USER_INFO,
                                Gson().toJson(codeStatus.result().userinfo())
                            )
                    }
                    getUserWxLoginStatus.value=codeStatus.result()
            },
            error = {
                messageStatus.value = "网络错误，请重试！"
            },
            cancel = {

            },
            showErrorToast = false
        )
    }
}